/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.subscription;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.model.forum.Forum;
import com.blandware.atleap.model.forum.ForumSubscription;
import com.blandware.atleap.model.forum.Topic;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.service.util.MailEngine;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.forum.ForumSubscriptionForm;
import com.blandware.atleap.webapp.util.core.ApplicationResources;
import com.blandware.atleap.webapp.util.core.GlobalProperties;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.RequestUtils;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.MailSendException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Creates an email subscription to forum or topic.</p>
 * <p><a href="CreateForumSubscriptionAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.6 $ $Date: 2008/04/29 17:51:51 $
 * @struts.action path="/forum/subscription/create"
 * name="forumSubscriptionForm"
 * scope="request"
 * input="inputForward"
 * validate="false"
 * @struts.action-forward name="inputForward"
 * path=".forum.subscription.create"
 * @struts.action-forward name="showForums"
 * path="/forum/forum/showForums.do"
 * redirect="true"
 * @struts.action-forward name="showForum"
 * path="/forum/forum/show.do"
 * redirect="true"
 * @struts.action-forward name="showTopic"
 * path="/forum/topic/show.do"
 * redirect="true"
 * @struts.action-forward name="activateSubscription"
 * path="/forum/subscription/activate.do"
 * redirect="true"
 * @struts.action-forward name="unsatisfiable"
 * path="/forum/forum/show.do"
 */
public final class CreateForumSubscriptionAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if (isCancelled(request)) {
            return mapping.findForward("showForum");
        }

        ForumSubscriptionForm forumSubscriptionForm = (ForumSubscriptionForm) form;

        HttpSession session = request.getSession();

        Long topicId = null;
        Long forumId = null;
        if (!GenericValidator.isBlankOrNull(request.getParameter("forumId"))) {
            try {
                forumId = Long.valueOf(request.getParameter("forumId"));
            } catch (NumberFormatException e) {
            }
        } else if (session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY) != null) {
            forumId = (Long) session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY);
        }
        if (!GenericValidator.isBlankOrNull(request.getParameter("topicId"))) {
            try {
                topicId = Long.valueOf(request.getParameter("topicId"));
            } catch (NumberFormatException e) {
            }
        } else if (session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY) != null) {
            topicId = (Long) session.getAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY);
        }

        if (forumId == null && topicId == null) {
            ActionMessages errors = new ActionMessages();
            errors.add("noTopicOrForumSpecified", new ActionMessage("forum.subscription.errors.noTopicOrForumSpecified"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        session.setAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY, forumId);
        session.setAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY, topicId);

        String remoteUser = request.getRemoteUser();
        boolean anonymous = remoteUser == null;

        if (anonymous) {
            if (GenericValidator.isBlankOrNull(forumSubscriptionForm.getEmail())) {
				// email must be specified
				ActionMessages errors = new ActionMessages();
				errors.add("email", new ActionMessage("core.commons.errors.required", getMessage(request, "forum.subscription.form.email")));
				saveErrors(request, errors, false);
				saveToken(request);
				return mapping.getInputForward();
            }
            if (!GenericValidator.isEmail(forumSubscriptionForm.getEmail())) {
                // email should be correct
				ActionMessages errors = new ActionMessages();
				errors.add("email", new ActionMessage("core.commons.errors.email", getMessage(request, "forum.subscription.form.email")));
				saveErrors(request, errors, false);
				saveToken(request);
				return mapping.getInputForward();
            }
        }

        session.removeAttribute(ForumModuleWebConstants.SUBSCRIPTION_FORUM_ID_KEY);
        session.removeAttribute(ForumModuleWebConstants.SUBSCRIPTION_TOPIC_ID_KEY);

        User user = null;
        if (!anonymous) {
            UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
            user = userManager.retrieveUser(remoteUser);
            if (user == null) {
                // no user found
                ActionMessages errors = new ActionMessages();
                errors.add("userNotFound", new ActionMessage("forum.subscription.errors.userNotFound"));
                saveErrors(request, errors);
                return mapping.findForward("showForum");
            }
        }

        boolean isForum = forumId != null;

        ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
        Forum forum = null;
        Topic topic = null;
        List roles = null;

        if (isForum) {
            forum = forumManager.retrieveForum(forumId);
            if (forum == null) {
                // no forum found
                ActionMessages errors = new ActionMessages();
                errors.add("topicOrForumNotFound", new ActionMessage("forum.subscription.errors.forumNotFound"));
                saveErrors(request, errors);
                return mapping.findForward("showForums");
            }
            roles = forum.getRoles();
        } else {
            topic = forumManager.retrieveTopic(topicId);
            if (topic == null) {
                // no topic found
                ActionMessages errors = new ActionMessages();
                errors.add("topicOrForumNotFound", new ActionMessage("forum.subscription.errors.topicNotFound"));
                saveErrors(request, errors);
                return mapping.findForward("showForum");
            }
            roles = topic.getForum().getRoles();
        }

        boolean isForumActive = (isForum ? forum.getActive() : topic.getForum().getActive()).booleanValue();
        if (!isForumActive) {
            // trying to subscribe to non-active forum or its topic
            ActionMessages errors = new ActionMessages();
            errors.add("notActive", new ActionMessage("forum.subscription.errors.notActive"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        try {
            if (!WebappUtil.isUserInRole(roles, false, "name", request)) {
                // insufficient rights
                ActionMessages errors = new ActionMessages();
                errors.add("notAllowed", new ActionMessage("forum.subscription.errors.notAllowed"));
                saveErrors(request, errors);
                return mapping.findForward("showForum");
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Exception while checking topic or forum roles", e);
            }
            return mapping.findForward("showForum");
        }

        ForumSubscription forumSubscription = new ForumSubscription();
        WebappUtil.copyProperties(forumSubscription, forumSubscriptionForm, request);

        boolean sendOk = true;
        Long subscriptionId = null;

        try {
            subscriptionId = forumManager.createSubscription(forumSubscription, forumId, topicId, remoteUser);

            if (anonymous) {
                ApplicationResources applicationResources = ApplicationResources.getInstance(servlet.getServletContext());
                String localeIdentifier = (RequestUtils.getUserLocale(request, null)).getLanguage();

                Map model = new HashMap();
                String forumOrTopicKey;
                String title;
                if (isForum) {
                    forumOrTopicKey = "forum.subscription.confirm.forum";
                    title = forum.getSingleTitle();
                } else {
                    forumOrTopicKey = "forum.subscription.confirm.topic";
                    title = topic.getFirstPostSubject();
                }
                Map parameters = new HashMap();
                parameters.put("id", subscriptionId);
                parameters.put("token", forumSubscription.getToken());
                String confirmUrl = WebappUtil.computeURL(mapping.findForward("activateSubscription").getPath(), null, null, null, parameters, request, response, false, false);
                StringBuffer uriBuffer = RequestUtils.createServerUriStringBuffer(request.getScheme(), request.getServerName(), request.getServerPort(), confirmUrl);
                confirmUrl = uriBuffer.toString();

                String uri = isForum ? ForumModuleWebUtil.getForumUri(forum)
                                     : ForumModuleWebUtil.getTopicUri(topic);
                StringBuffer urlBuffer = null;
                String url = null;
                try {
                    uri = WebappUtil.computeURL(uri, null, null, null, null, request, response, false, false);
                    urlBuffer = RequestUtils.createServerUriStringBuffer(request.getScheme(), request.getServerName(), request.getServerPort(), uri);
                    url = urlBuffer.toString();
                } catch (MalformedURLException e) {
                    url = "";
                }

                model.put("forumOrTopic", applicationResources.getMessage(request, forumOrTopicKey));
                model.put("title", title);
                model.put("confirmUrl", confirmUrl);
                model.put("url", url);

                // send message
                MailEngine mailEngine = (MailEngine) getBean(Constants.MAIL_ENGINE_BEAN);
                String contactAddress = user != null ? user.getEmail() : forumSubscription.getEmail();
                String fromAddress = GlobalProperties.getInstance(request.getSession().getServletContext()).getString(ForumModuleConstants.FORUM_FROM_ADDRESS);
                try {
                    mailEngine.sendMessage(fromAddress, null, new String[]{contactAddress}, null, null, "confirmForumSubscription", localeIdentifier, model);
                } catch ( MailPreparationException e ) {
                    if ( log.isErrorEnabled() ) {
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw));
                        log.error(sw.toString());
                    }
                    ActionMessages errors = new ActionMessages();
                    errors.add("preparationFailed", new ActionMessage("forum.subscription.errors.preparationFailed"));
                    saveErrors(request, errors);
                    sendOk = false;
                } catch ( MailSendException e ) {
                    if ( log.isErrorEnabled() ) {
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw));
                        log.error(sw.toString());
                    }
                    ActionMessages errors = new ActionMessages();
                    errors.add("sendFailed", new ActionMessage("forum.subscription.errors.sendFailed"));
                    saveErrors(request, errors);
                    sendOk = false;
                } catch ( Exception e ) {
                    if ( log.isErrorEnabled() ) {
                        StringWriter sw = new StringWriter();
                        e.printStackTrace(new PrintWriter(sw));
                        log.error(sw.toString());
                    }
                    ActionMessages errors = new ActionMessages();
                    errors.add("unknownError", new ActionMessage("forum.subscription.errors.unknownError"));
                    saveErrors(request, errors);
                    sendOk = false;
                }
            }
        } catch (OwnerNotFoundException e) {
            ActionMessages errors = new ActionMessages();
            errors.add("ownerNotFound", new ActionMessage("forum.subscription.errors.ownerNotFound"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        } catch (BeanAlreadyExistsException e) {
            ActionMessages errors = new ActionMessages();
            errors.add("alreadySubscribed", new ActionMessage("forum.subscription.errors.alreadySubscribed"));
            saveErrors(request, errors);
            return mapping.findForward("showForum");
        }

        if (anonymous && !sendOk) {
            try {
                forumManager.deleteSubscription(subscriptionId, forumSubscription.getToken());
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error("Could not delete forum subscription after confirmation email send failed");
                }
            }
        } else {
            ActionMessages messages = new ActionMessages();
            if (anonymous) {
                messages.add("success", new ActionMessage("forum.subscription.messages.successfullySubscribedNotActive"));
            } else {
                messages.add("success", new ActionMessage("forum.subscription.messages.successfullySubscribedActive"));
            }
            saveMessages(request, messages);
        }
        return mapping.findForward("showForum");
	}
}
